package com.itheima_2;

public class MyRunnable implements  Runnable{
    private /*static*/ int ticketCount=100;

    @Override
    public void run() {
        while (true){
            if("窗口一".equals(Thread.currentThread().getName())){
                //同步方法,锁对象是this
                boolean b = synchronizedMethod();
                if(b){
                        break;
                }
            }
            if("窗口二".equals(Thread.currentThread().getName())){
                //同步代码块
                //同步静态方法锁对象是 (类名.class)
                synchronized (/*MyRunnable.class*/this){
                    if (ticketCount == 0) {
                        break;
                    } else {
                        try {
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        ticketCount--;
                        System.out.println(Thread.currentThread().getName() + "在卖票还剩下" + ticketCount + "张票");
                    }
                }
            }
        }
    }

    private /*static*/ synchronized boolean synchronizedMethod() {
        if (ticketCount == 0) {
            return true;
        } else {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ticketCount--;
            System.out.println(Thread.currentThread().getName() + "在卖票还剩下" + ticketCount + "张票");
            return false;
        }
    }
}
